//
//  SerceCollectionViewController.m
//  ForestPack
//
//  Created by 郑洲 on 2018/7/4.
//  Copyright © 2018年 郑洲. All rights reserved.
//

#import "ServeCollectionViewController.h"

#import "FPCommodityDetailVC.h"
#import "ServeCollectionCell.h"

@interface ServeCollectionViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) BaseTableView *tableView;

@property (nonatomic,strong)  NSMutableArray  * dataArray;

@property (nonatomic,assign)  NSInteger       page;
@property (nonatomic,assign)  NSInteger       current_page;

@end

@implementation ServeCollectionViewController

- (NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"服务收藏";
    
    self.tableView = [[BaseTableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVIGATION_BAR_HEIGHT)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.rowHeight = ScreenX375(101);
    [self.view addSubview:self.tableView];
    
    [self refreshTableView];
}

-(void)refreshTableView
{
    /** 为了避免 block 的循环引用导致内存泄漏  要使用__weakSelf 来代替self */
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.current_page = 1;
        [weakSelf requestData];
    }];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf requestMoreData];
    }];
    [self.tableView.mj_header beginRefreshing];
}

-(void)requestData
{
    NSString *url = [NSString stringWithFormat:@"%@app/service_collection",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":@"1",@"longitude":kNSUDefaultReadKey(@"longitude"),@"latitude":kNSUDefaultReadKey(@"latitude")};
    
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self.tableView.mj_header endRefreshing];
            NSError *error;
            
            [self.dataArray removeAllObjects];
            self.page = [successResponse[@"data"][@"last_page"] integerValue];
            // 成功
            for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                ServeGoodsDataModel *model = [[ServeGoodsDataModel alloc] initWithDictionary:dic error:&error];
                if (model != nil) {
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
            
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_header endRefreshing];
        [HttpManager showFail];
    }];
}

-(void)requestMoreData
{
    self.current_page++;
    NSString *url = [NSString stringWithFormat:@"%@app/service_collection",REQUESTHEADER];
    NSDictionary *dict = @{@"token":[FPLoginAndRegisterTools getToken],@"page":[NSNumber numberWithInteger:self.current_page],@"longitude":kNSUDefaultReadKey(@"longitude"),@"latitude":kNSUDefaultReadKey(@"latitude")};
    [HttpManager postHttpRequestByPost:url andParameter:dict success:^(id successResponse) {
        NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
        if ([status isEqualToString:@"1"]) {
            [self.tableView.mj_footer endRefreshing];
            NSError *error;
            // 成功
            self.page = [successResponse[@"data"][@"last_page"] integerValue];
            // 成功
            for (NSDictionary *dic in successResponse[@"data"][@"data"]) {
                ServeGoodsDataModel *model = [[ServeGoodsDataModel alloc] initWithDictionary:dic error:&error];
                if (model != nil) {
                    [self.dataArray addObject:model];
                }
            }
            [self.tableView reloadData];
            
        }else{
            [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
        }
    } andFailure:^(id failureResponse) {
        [self.tableView.mj_footer endRefreshing];
        [HttpManager showFail];
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    ServeCollectionCell *cell = [ServeCollectionCell cellWithTableView:tableView andIndexPath:indexPath];
    cell.serveGoodsDataModel = _dataArray[indexPath.row];
    ServeGoodsDataModel *model = self.dataArray[indexPath.row];
    cell.cancelConcernClick = ^{
        [HttpManager postHttpRequestByPost:[NSString stringWithFormat:@"%@app/collect_service",REQUESTHEADER] andParameter:@{@"token":[FPLoginAndRegisterTools getToken],@"goods_id":model.Id} success:^(id successResponse) {
            NSString *status = [NSString stringWithFormat:@"%@",successResponse[@"status"]];
            if ([status isEqualToString:@"1"]) {
                [HttpManager showNoteMsg:@"取消收藏成功"];
                [self.dataArray removeObjectAtIndex:indexPath.row];
                [self.tableView reloadData];
            }else{
                [HttpManager showNoteMsg:[NSString stringWithFormat:@"%@",successResponse[@"msg"]]];
            }
        } andFailure:^(id failureResponse) {
            [HttpManager showFail];
        }];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ServeGoodsDataModel *model = self.dataArray[indexPath.row];
    FPCommodityDetailVC *vc = [[FPCommodityDetailVC alloc] init];
    vc.design_id = [model.Id integerValue];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
